package com.ziyucoding.springboot.labs.lab4.concurrentdemo.example.synccontainer;

import com.ziyucoding.springboot.labs.lab4.concurrentdemo.annoations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Vector;


/**
 * Vector 示例3
 *
 * @author ziyucoding
 * @date 2022-10-26
 **/
@Slf4j
@NotThreadSafe
public class VectorExample3 {

    public static void main(String[] args) throws InterruptedException {
        Vector<Integer> items = new Vector<>();
        for (int i = 0; i < 8; i++) {
            items.add(i);
        }
//        testForEach(items);
//        testIterator(items);
        testFor(items);
    }

    /**
     * foreach
     *
     * @param items
     * @return void
     **/
    private static void testForEach(Vector<Integer> items) {
        for (Integer item : items) {
            if (item == 2) {
                items.remove(item);
                // java.util.ConcurrentModificationException
            }
        }
    }

    /**
     * Iterator
     *
     * @param items
     * @return void
     **/
    private static void testIterator(Vector<Integer> items) {
        Iterator<Integer> iterator = items.iterator();
        while (iterator.hasNext()) {
            Integer item = iterator.next();
            if (item == 2) {
                items.remove(item);
                // java.util.ConcurrentModificationException
            }
        }
    }

    /**
     * for
     *
     * @param items
     * @return void
     **/
    private static void testFor(Vector<Integer> items) {
        for (int i = 0; i < items.size(); i++) {
            if (items.get(i) == 2) {
                items.remove(2);
                // success
            }
        }
    }
}
